<template>
	<view class="address-container">
		<!-- 地址列表 -->
		<view class="address-list" v-if="addressList && addressList.length > 0">
			<view class="address-item" v-for="item in addressList" :key="item.id"
				@click="fromPage === 'cart' && handleTemporaryAddress(item)">
				<view class="main-info">
					<view class="user-info">
						<text class="name">{{ item.name }}</text>
						<text class="phone">{{ item.tel }}</text>
						<text class="tag" v-if="item.isDefault">默认</text>
					</view>
					<view class="address-detail">
						<image src="/static/images/location.png" mode="aspectFit" class="location-icon"></image>
						<text class="detail-text">{{ item.province }}{{ item.city }}{{ item.district }}{{ item.address
							}}</text>
					</view>
				</view>
				<view class="action-bar">
					<view class="left-actions">
						<radio :checked="item.isDefault" @click="setDefault(item)" class="radio" color="#ff4444"
							v-if="fromPage !== 'user'">
						</radio>
						<text class="default-text" :class="{ 'active': item.isDefault }"
							v-if="fromPage !== 'user'">设为默认</text>
					</view>
					<view class="right-actions">
						<view class="btn-group">
							<text class="btn" @tap.stop="deleteAddress(item)">删除</text>
							<text class="btn" @tap.stop="copyAddress(item)">复制</text>
							<text class="btn" @tap.stop="editAddress(item)">修改</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-tip" v-else>
			<text>暂无收货地址</text>
		</view>

		<!-- 底部添加按钮 -->
		<view class="add-btn" @tap="addAddress">
			新增收货地址
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reqUserAddressList, reqDelUserAddress, reqUpdUserAddress } from '@/api/user.js';
import { useUserStore } from '@/store';
import { useCartStore } from '@/store/modules/cart';

const cartStore = useCartStore();
const userStore = useUserStore();

// 地址列表
const addressList = ref([]);
// 来源页面标识
const fromPage = ref('');

// 获取地址列表
const getAddressList = async () => {
	try {
		const res = await reqUserAddressList()
		addressList.value = res;
		userStore.addressList = res;
	} catch (error) {
		console.error('获取地址列表失败:', error);
		uni.showToast({
			title: '获取地址列表失败',
			icon: 'none'
		});
	}
};

// 处理临时地址选择（仅在购物车来源时可用）
const handleTemporaryAddress = (item) => {
	if (fromPage.value === 'cart') {
		cartStore.temporaryAddress = item;
		console.log(cartStore.temporaryAddress);
		uni.switchTab({
			url: '/pages/cart/cart'
		});
	}
};

// 页面加载
onLoad((options) => {
	if (options.from) {
		fromPage.value = options.from;
	}
	getAddressList();
});

// 页面显示时刷新数据
onShow(() => {
	getAddressList();
});

// 删除地址
const deleteAddress = async (item) => {
	try {
		await reqDelUserAddress(item.id);
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		});
		getAddressList();
	} catch (error) {
		uni.showToast({
			title: '删除失败',
			icon: 'none'
		});
	}
};

// 复制地址
const copyAddress = (item) => {
	const fullAddress = `${item.province}${item.city}${item.district}${item.address}`;
	uni.setClipboardData({
		data: fullAddress,
		success: () => {
			uni.showToast({
				title: '地址已复制',
				icon: 'success'
			});
		}
	});
};

// 编辑地址
const editAddress = (item) => {
	uni.navigateTo({
		url: `/pages/address_package/address/edit?id=${item.id}`,
		success: () => {
			// 将完整的地址信息存储到本地，供编辑页面使用
			uni.setStorageSync('editAddressData', item);
		}
	});
};

// 新增地址
const addAddress = () => {
	uni.navigateTo({
		url: '/pages/address_package/address/edit'
	});
};

// 设置默认地址（仅在非用户页面来源时可用）
const setDefault = async (item) => {
	if (fromPage.value === 'user') return;

	try {
		// 只传递必要的字段
		await reqUpdUserAddress({
			...item,
			isDefault: !item.isDefault
		});

		// 重新获取地址列表
		getAddressList();

		if (fromPage.value === 'cart') {
			uni.switchTab({
				url: '/pages/cart/cart'
			});
			cartStore.temporaryAddress = null;
		}

		uni.showToast({
			title: !item.isDefault ? '已设为默认地址' : '已取消默认地址',
			icon: 'success'
		});
	} catch (error) {
		console.error('设置默认地址失败:', error);
		uni.showToast({
			title: '设置失败',
			icon: 'none'
		});
	}
};
</script>

<style lang="scss" scoped>
@import '@/uni.scss';

.address-container {
	min-height: 100vh;
	background-color: #f7f7f7;
	padding: 20rpx;

	.address-list {
		.address-item {
			margin-bottom: 20rpx;
			background-color: #fff;
			padding: 30rpx;
			border-radius: 12rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.main-info {
				.user-info {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;

					.name {
						font-size: 32rpx;
						color: #333;
						margin-right: 20rpx;
						font-weight: 500;
					}

					.phone {
						font-size: 28rpx;
						color: #666;
					}

					.tag {
						margin-left: auto;
						font-size: 22rpx;
						color: #ff4444;
						border: 1px solid #ff4444;
						padding: 2rpx 12rpx;
						border-radius: 20rpx;
					}
				}

				.address-detail {
					display: flex;
					align-items: flex-start;

					.location-icon {
						width: 32rpx;
						height: 32rpx;
						margin-right: 10rpx;
						flex-shrink: 0;
					}

					.detail-text {
						font-size: 28rpx;
						color: #333;
						line-height: 1.5;
					}
				}
			}

			.action-bar {
				margin-top: 30rpx;
				padding-top: 20rpx;
				border-top: 1px solid #f5f5f5;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.left-actions {
					display: flex;
					align-items: center;

					.radio {
						transform: scale(0.8);
						margin-right: 8rpx;
					}

					.default-text {
						font-size: 26rpx;
						color: #666;

						&.active {
							color: #ff4444;
							font-weight: 500;
						}
					}
				}

				.right-actions {
					.btn-group {
						display: flex;
						align-items: center;

						.btn {
							font-size: 26rpx;
							color: #666;
							padding: 0 20rpx;
							position: relative;

							&:not(:last-child)::after {
								content: '';
								position: absolute;
								right: 0;
								top: 50%;
								transform: translateY(-50%);
								width: 1px;
								height: 24rpx;
								background-color: #eee;
							}

							&:active {
								opacity: 0.7;
							}
						}
					}
				}
			}
		}
	}

	.add-btn {
		position: fixed;
		left: 20rpx;
		right: 20rpx;
		bottom: 20rpx;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		background-color: #ff4444;
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
		box-shadow: 0 4rpx 16rpx rgba(255, 68, 68, 0.3);
	}

	.empty-tip {
		padding: 120rpx 0;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}
}
</style>